import sys
import os
import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class MaintenanceUpdater:
    def __init__(self):
        self.db = Database()
    
    def update_maintenance_status(self, maintenance_id, new_status):
        """
        更新维修记录状态
        
        参数:
            maintenance_id (int): 维修记录ID
            new_status (str): 新状态 (pending, in_progress, completed)
        
        返回:
            bool: 更新成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not maintenance_id or not new_status:
                print("错误：维修记录ID和新状态都必须填写")
                return False
            
            if new_status not in ['pending', 'in_progress', 'completed']:
                print("错误：状态必须是'pending'、'in_progress'或'completed'")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查维修记录是否存在
            self.db.cursor.execute(
                """SELECT m.id, d.building, d.room_number, m.status, m.dormitory_id 
                   FROM maintenance m 
                   JOIN dormitory d ON m.dormitory_id = d.id 
                   WHERE m.id = ?""",
                (maintenance_id,)
            )
            maintenance = self.db.cursor.fetchone()
            
            if not maintenance:
                print(f"错误：ID为 {maintenance_id} 的维修记录不存在")
                self.db.close()
                return False
            
            # 如果状态没有变化，则不需要更新
            if maintenance[3] == new_status:
                print(f"维修记录 {maintenance_id} 的状态已经是 {new_status}")
                self.db.close()
                return True
            
            # 获取当前日期
            current_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            
            # 更新维修记录状态
            if new_status == 'completed':
                # 如果状态更新为已完成，则设置解决日期
                self.db.cursor.execute(
                    "UPDATE maintenance SET status = ?, resolved_date = ? WHERE id = ?",
                    (new_status, current_date, maintenance_id)
                )
                
                # 如果维修完成，将宿舍状态更新为可用
                self.db.cursor.execute(
                    "UPDATE dormitory SET status = 'available' WHERE id = ?",
                    (maintenance[4],)
                )
            else:
                # 其他状态更新，不设置解决日期
                self.db.cursor.execute(
                    "UPDATE maintenance SET status = ? WHERE id = ?",
                    (new_status, maintenance_id)
                )
            
            self.db.conn.commit()
            
            status_display = "待处理" if new_status == 'pending' else "处理中" if new_status == 'in_progress' else "已完成"
            old_status_display = "待处理" if maintenance[3] == 'pending' else "处理中" if maintenance[3] == 'in_progress' else "已完成"
            
            print(f"成功：宿舍 {maintenance[1]}-{maintenance[2]} 的维修记录状态已从 {old_status_display} 更新为 {status_display}")
            if new_status == 'completed':
                print(f"完成时间：{current_date}")
                print(f"宿舍状态已更新为可用")
            
            return True
        except Exception as e:
            print(f"错误：更新维修记录状态时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    updater = MaintenanceUpdater()
    
    print("===== 维修状态更新 =====")
    
    # 查询所有维修记录
    db = Database()
    db.connect()
    db.cursor.execute(
        """SELECT m.id, d.building, d.room_number, m.issue_description, 
           m.report_date, m.status, m.resolved_date 
           FROM maintenance m 
           JOIN dormitory d ON m.dormitory_id = d.id 
           ORDER BY m.report_date DESC"""
    )
    records = db.cursor.fetchall()
    db.close()
    
    if not records:
        print("没有找到任何维修记录")
    else:
        print("\n记录ID\t宿舍\t\t问题描述\t\t报修时间\t\t状态\t\t解决时间")
        for record in records:
            resolved_date = record[6] if record[6] else "未解决"
            status_display = "待处理" if record[5] == 'pending' else "处理中" if record[5] == 'in_progress' else "已完成" if record[5] == 'completed' else record[5]
            print(f"{record[0]}\t{record[1]}-{record[2]}\t{record[3][:10]}...\t{record[4]}\t{status_display}\t{resolved_date}")
        
        try:
            maintenance_id = int(input("\n请输入要更新的维修记录ID: "))
            
            print("\n状态选项:")
            print("1. pending - 待处理")
            print("2. in_progress - 处理中")
            print("3. completed - 已完成")
            
            status_choice = input("请选择新状态 (1-3): ")
            
            status = None
            if status_choice == '1':
                status = 'pending'
            elif status_choice == '2':
                status = 'in_progress'
            elif status_choice == '3':
                status = 'completed'
            else:
                print("错误：无效的状态选择")
                exit()
            
            updater.update_maintenance_status(maintenance_id, status)
        except ValueError:
            print("错误：维修记录ID必须是数字")